
package com.epam.android.training.day6;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * Main Activity for this project. Shows contact's phones. When user clicks on
 * the contact, it starts calling.
 * 
 * @author Natallia_Kukharchyk
 */
public class MainPage extends ListActivity {

  private static final String[] PHONE_PROJECTION = new String[] {
      Phone._ID, Phone.NUMBER, Phone.DISPLAY_NAME,
  };

  /**
   * fields to display
   */
  private static final String[] COLUMNS = new String[] {
      Phone.DISPLAY_NAME, Phone.NUMBER
  };

  /**
   * view fields
   */
  private static final int[] TO = new int[] {
      android.R.id.text1, android.R.id.text2
  };

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Cursor c = getContentResolver().query(Phone.CONTENT_URI, PHONE_PROJECTION, null, null, null);
    startManagingCursor(c);

    // using simple cursor adapter to map data to view (shows name & phone)
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_list_item_2, c,
        COLUMNS, TO);

    setListAdapter(adapter);
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    Intent i = new Intent(Intent.ACTION_CALL);
    TextView tv1 = (TextView) v.findViewById(android.R.id.text2);
    // make a call
    i.setData(Uri.parse("tel:" + tv1.getText()));
    startActivity(i);

  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // creates menu
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;

  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // starts other activity which shows data from custom content provider
      case R.id.custom_prov:
        Intent intent = new Intent(getApplicationContext(), MyContentView.class);
        startActivity(intent);
        break;
    }
    return true;
  }
}
